package com.ics.cmsadmin.frame.utils;

import com.ics.cmsadmin.frame.core.bean.ApiResponse;
import com.ics.cmsadmin.frame.core.enums.ApiResultEnum;
import com.ics.cmsadmin.frame.core.exception.ExceptionUtils;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.io.IOUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * Created by lvsw on 2018/8/25.
 */
@Log4j2
public final class HttpUtils {
    /**
     * 设置响应体返回json数据
     */
    public static void setJsonDataResponse(HttpServletResponse response, ApiResponse apiResponse, int stauts) {
        try {
            response.setHeader("Context-type", "application/json;charset=utf-8");
            response.setStatus(stauts);
            IOUtils.write(GsonUtils.toJson(apiResponse), response.getOutputStream(), "utf-8");
        } catch (Exception e) {
            log.error(ExceptionUtils.collectExceptionStackMsg(e));
        }
    }

    /**
     * 校验表单输入内容
     */
    public static ApiResponse validateError(BindingResult bindingResult) {
        StringBuilder sb = new StringBuilder();
        List<ObjectError> allErrors = bindingResult.getAllErrors();
        for (ObjectError error : allErrors){
            sb.append(error.getDefaultMessage()).append("\n");
        }
        return new ApiResponse(ApiResultEnum.VALIDATE_ERROR, sb.toString());
    }
}
